package com.cloud.pikachu.dingtalk.service.login;

import com.cloud.pikachu.dingtalk.api.AvoidLandingAPI;
import com.cloud.pikachu.dingtalk.api.UserAPI;
import com.cloud.pikachu.dingtalk.bean.AvoidLandingResponse;
import com.cloud.pikachu.dingtalk.bean.common.UserInfo;
import com.cloud.pikachu.dingtalk.service.token.AccessTokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 免登陆Service
 */
@Service
public class AvoidLoginService {
    private static final Logger logger = LoggerFactory.getLogger(AvoidLoginService.class);

    @Autowired
    private AccessTokenService accessTokenService;

    /**
     * 免登陆获取用户信息
     * @param code
     * @return
     */
    public UserInfoModel avoidLogin(String code){
        UserInfoModel userInfoModel = new UserInfoModel();

        try{
            AvoidLandingResponse avoidLandingResponse = AvoidLandingAPI.getUserInfo(accessTokenService.getAccessToken() , code);
            if(avoidLandingResponse==null || avoidLandingResponse.getErrcode()!=0){
                throw new Exception("授权码，免登陆失败");
            }
            avoidLandingResponse.getUserid();
            UserInfo userInfo = UserAPI.getUserInfo(accessTokenService.getAccessToken() , avoidLandingResponse.getUserid());
            userInfoModel.setActive(userInfo.isActive());
            userInfoModel.setAdmin(userInfo.isAdmin());
            userInfoModel.setAvatar(userInfo.getAvatar());
            userInfoModel.setBoss(userInfo.isBoss());
            userInfoModel.setDepartment(userInfo.getDepartment());
            userInfoModel.setDingId(userInfo.getDingId());
            userInfoModel.setEmail(userInfo.getEmail());
            userInfoModel.setMobile(userInfo.getMobile());
            userInfoModel.setName(userInfo.getName());
            userInfoModel.setRemark(userInfo.getRemark());
            userInfoModel.setTel(userInfo.getTel());
            userInfoModel.setUserid(userInfo.getUserid());
            userInfoModel.setCode(200);
            userInfoModel.setMsg("OK");

        }catch (Exception ex){
            logger.info("授权登录失败"  , ex.getMessage());
            userInfoModel.setCode(500);
            userInfoModel.setMsg("授权码，免登陆失败");

        }
        return userInfoModel;
    }
}
